import requests
def fetch_webpage(url, output_file):
    try:
        # 模拟浏览器，发送请求
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
        }
        # 发送HTTP GET请求
        response = requests.get(url,headers=headers)

        # 检查请求是否成功
        response.raise_for_status()  # 如果请求失败，将引发HTTPError异常

        # 获取网页源码
        webpage_source = response.text

        # 将网页源码写入HTML文件
        with open(output_file, 'w', encoding='utf-8') as file:
            file.write(webpage_source)

        print(f"网页源码已成功保存到 {output_file}")
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")


# 示例使用
url = 'https://www.huya.com/g/4079'  # 替换为你要爬取的网页URL
output_file = 'wenjian/huya.html'  # 替换为你想要保存的HTML文件名
fetch_webpage(url, output_file)